<template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="5" :offset="0">
            <el-form-item label="公司名称">
              <el-input v-model="searchForm.name" placeholder="公司名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
  
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="公司名称" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.name }}
          </template>
        </el-table-column>
  
        <el-table-column label="公司注册地址" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.address }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="公司描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.description }}
          </template>
        </el-table-column> -->

        <el-table-column label="公司成立时间" align="center">
          <template #default="{ row }">
            {{ row.establishmentTime }}
          </template>
        </el-table-column>

        <el-table-column label="公司电话" align="center">
          <template #default="{ row }">
            {{ row.phone }}
          </template>
        </el-table-column>

        <el-table-column label="公司邮箱" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.email }}
          </template>
        </el-table-column>

        <el-table-column label="创建人" align="center">
          <template #default="{ row }">
            {{ row.createUsername }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
                <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>

                <el-button type="primary" size="small" text @click="showCompanyManager(scope.row)">项目联系人</el-button>

                <el-popconfirm title="是否要删除该公司以及其负责人？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="clickDeleteBtn(scope.row.id)">
                    <template #reference>
                        <el-button text type="primary" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="initTableData" />
      </div>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
          
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="form.name" placeholder="公司名称"></el-input>
          </el-form-item>

          <!-- <el-form-item label="公司描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="form.description" placeholder="公司描述"></el-input>
          </el-form-item> -->

          <el-form-item label="注册地址" prop="address">
            <el-input v-model="form.address" placeholder="公司注册地址"></el-input>
          </el-form-item>

          <el-form-item label="成立时间" prop="establishmentTime">
              <el-date-picker
                v-model="form.establishmentTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD">
              </el-date-picker>
          </el-form-item>

          <el-form-item label="公司电话" prop="phone">
            <el-input v-model="form.phone" placeholder="公司电话"></el-input>
          </el-form-item>

          <el-form-item label="公司邮箱" prop="email">
            <el-input v-model="form.email" placeholder="公司邮箱"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>

      <!-- 设置公司负责人弹窗 -->
      <FormDrawer size="70%" ref="companyManagerListDrawerRef" title="项目联系人列表" showSubBtn="0" @isClosed="isClosed" @submit="handleSubmit">
          <SelectCompanyManager v-if="showCompanyManagerTable" :companyId="companyId"></SelectCompanyManager>
      </FormDrawer>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import SelectCompanyManager from "~/components/select-company-manager.vue";
import {toast,toastWarn} from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { getCompanyList,addCompany,updateCompany,deleteCompany } from "~/api/userApi"

// 公司负责人弹窗相关参数
const companyId = ref(null)
const companyManagerListDrawerRef = ref(null)
const showCompanyManagerTable = ref(false)

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
  name: "",
  page: currentPage.value,
  size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
  searchForm.name = ""
  initTableData(1)
}

const tableData = ref([])
const loading = ref(false)


// 生命周期函数
onMounted(() => {
  //初始化列表数据
  initTableData()
})


// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getCompanyList(searchForm)
    .then(res => {
       if(res){
          tableData.value = res.records      
          total.value = res.total
        }else{
          tableData.value = []  
          total.value = 0
        }
    })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  name: "",
  address: "",
  description: "",
  phone: "",
  email: "",
  establishmentTime: null
})
//执行表单校验
const rules = {
  name: [
    { required: true, message: '公司名称不能为空', trigger: 'change' }
  ],
  // address: [
  //   { required: true, message: '公司注册地址不能为空', trigger: 'change' }
  // ],
  description: [
    { required: true, message: '公司描述不能为空', trigger: 'change' }
  ],
  // establishmentTime: [
  //   { required: true, message: '公司成立时间不能为空', trigger: 'change' }
  // ],
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //loading
        formDrawerRef.value.showLoading()
        //根据是否是修改标记，判断执行新增接口还是修改接口
        const fun = editId.value ? updateCompany(editId.value, form) : addCompany(form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            initTableData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
    })
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    name: "",
    address: "",
    description: "",
    phone: "",
    email: "",
    establishmentTime: null
  })
  //打开弹窗
  formDrawerRef.value.open()
}

// 编辑
const handleEdit = (row) => {
  editId.value = row.id
  resetForm(row)
  formDrawerRef.value.open()
}

// 删除
const clickDeleteBtn = (id) => {
  loading.value = true
  deleteCompany(id).then(res => {
      toast("删除成功")
      initTableData()
  })
  .finally(() => {
      loading.value = false
  })
}

//点击负责人按钮
const showCompanyManager = (row) => {
    companyId.value = row.id
    companyManagerListDrawerRef.value.open()
    showCompanyManagerTable.value = true
}

//弹窗关闭通知父组件
function isClosed() {
    showCompanyManagerTable.value = false
}
</script>